package com.example.calculator

import android.app.Application
import android.content.Context
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.SavedStateHandle
import kotlin.random.Random

class MyViewModel(application: Application,private var handle:SavedStateHandle) : AndroidViewModel(application) {
    public var winFlag:Boolean=false
    init {
        //首次使用，初始化
        if(!handle.contains(KEY_HIGHEST_SCORE)){

           var shp=getApplication<Application>()
               .getSharedPreferences(KEY_SHARE,Context.MODE_PRIVATE)
            //在磁盘中存储最高分
            if(shp.contains(KEY_HIGHEST_SCORE)){
                var score=shp.getInt(KEY_HIGHEST_SCORE,0)
                handle!!.set(KEY_HIGHEST_SCORE,score)
            }else{
                shp.edit().putInt(KEY_HIGHEST_SCORE,0).apply()
                //设置默认最高分
                handle.set(KEY_HIGHEST_SCORE,0)
            }
            //设置默认的表达式
            var expression=Expression(0,0,'+',0)
            handle.set(KEY_EXPRESSION,expression)
            //设置默认的当前得分
            handle.set(KEY_CURRENTSCORE,0)

        }
    }
    fun getHighestScore():MutableLiveData<Int>{
        return handle.getLiveData(KEY_HIGHEST_SCORE)
    }
    fun getCurrentScore():MutableLiveData<Int>{
        return handle.getLiveData(KEY_CURRENTSCORE)
    }
    fun getExpression():MutableLiveData<Expression> {
        return handle.getLiveData(KEY_EXPRESSION)
    }

    /**
     * 随机生成题目
     */
    fun generator(){
        var Level=20
        var random:Random= Random(System.currentTimeMillis())
        var expression=Expression(random.nextInt(Level)+1,random.nextInt(Level)+1,'+',0)
//        随机取符号
        var list= listOf<Char>('+','-')
        var r= Random(System.currentTimeMillis())
        expression.operator=list[r.nextInt(2)]
        if (expression.operator.equals('-')&&expression.num1<expression.num2){
            var tmp=expression.num1
            expression.num1=expression.num2
            expression.num2=tmp
        }
        //放入handle中
        getExpression().value=expression
    }

    /**
     * 保存最高分数
     */
    fun save(){
        getApplication<Application>()
            .getSharedPreferences(KEY_SHARE,Context.MODE_PRIVATE)
            .edit()
            .putInt(KEY_HIGHEST_SCORE, getHighestScore().value!!)
            .apply()
    }

    /**
     * 当前题目回答正确
     */
    fun answerCorret(){
        getCurrentScore().value = getCurrentScore().value?.plus(1)
        //若当前分数超过最高分数，则胜利，并且重置最高分
        if (getCurrentScore().value!! > getHighestScore().value!!){
            getHighestScore().value=getCurrentScore().value
            winFlag=true
        }
        //生成下一道题
        generator()
    }

    companion object {
        private const val KEY_HIGHEST_SCORE="high_score"
        private const val KEY_EXPRESSION="expression"
        private const val KEY_SHARE="shpName"
        private const val KEY_CURRENTSCORE="score"
    }
}